import random
import time
import xlrd
from datetime import datetime
import os
import shutil


class UploadUtils():
    # 上传文件
    def upload_file(self, file, upload_dir, suffix):

        """
        suffix支持： "xcupdate" "xcsettings" "xcflow"
        """
        __ret = False
        __msg = "未知错误"
        __info = {}
        try:
            file_name = file.name  # 上传文件的名称 xcms.4.609.x64.ubuntu20.ov.xcupdate
            # file_size = file.size  # 上传文件的字节大小 1M = 1024*1024, 100M = 100*1024*1024 = 104857600
            # file_size_m = int(file_size / 1024 / 1024)
            # file_content_type = file.content_type  # 上传文件的 file_content_type = application/octet-stream
            if file_name.endswith(".%s"%suffix):
                if not os.path.exists(upload_dir):
                    os.makedirs(upload_dir)

                # 自定义存储名称
                import_name = "%s-%s" % (suffix,datetime.now().strftime("%Y%m%d%H%M%S"))  # xcupdate-20240531121108
                import_dir = os.path.join(upload_dir, import_name)                        # /xxx/xcupdate-20240531121108
                import_tar_filepath = os.path.join(upload_dir, import_name + ".tar")      # /xxx/xcupdate-20240531121108.tar

                # 将上传文件写入到本地
                f = open(import_tar_filepath, 'wb')
                f.write(file.read())
                f.close()

                __ret = True
                __msg = "success"

                __info["import_name"] = import_name
                __info["import_dir"] = import_dir
                __info["import_tar_filepath"] = import_tar_filepath
            else:
                __msg = "上传文件格式必须是.%s"%suffix
        except Exception as e:
            __msg = "upload_file() error:" + str(e)

        return __ret, __msg, __info
    # 上传文件（方式2）
    def upload_file2(self, file, upload_dir):
        __ret = False
        __msg = "未知错误"
        __filename = None
        __filepath = None
        try:
            file_name = file.name  # 上传文件的名称 xcms.4.609.x64.ubuntu20.ov.xcupdate
            # file_size = file.size  # 上传文件的字节大小 1M = 1024*1024, 100M = 100*1024*1024 = 104857600
            # file_size_m = int(file_size / 1024 / 1024)
            # file_content_type = file.content_type  # 上传文件的 file_content_type = application/octet-stream
            if not os.path.exists(upload_dir):
                os.makedirs(upload_dir)

            __filename = "xc%s-%s" % (datetime.now().strftime("%Y%m%d%H%M%S"),file_name)
            __filepath = os.path.join(upload_dir, __filename)

            # 将上传文件写入到本地
            f = open(__filepath, 'wb')
            f.write(file.read())
            f.close()

            __ret = True
            __msg = "success"

        except Exception as e:
            __msg = "upload_file2() error:" + str(e)

        return __ret, __msg, __filename,__filepath

    # 上传摄像头文件（批量导入摄像头）
    def upload_camera_xlsx(self, file, upload_dir):
        __ret = False
        __msg = "未知错误"
        __data = []

        file_name = file.name  # 上传文件的名称
        # file_size = file.size  # 上传文件的字节大小 1M = 1024*1024, 100M = 100*1024*1024 = 104857600
        # file_size_m = int(file_size / 1024 / 1024)
        file_content_type = file.content_type  # 上传文件的 content_type
        # print("file_content_type=",file_content_type)
        if 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' == file_content_type and file_name.endswith(
                ".xlsx"):
            filename_dir = datetime.now().strftime("%Y%m%d%H%M%S") + "_" + file_name  # 相对路径
            abs_filedir = os.path.join(upload_dir, filename_dir)
            if not os.path.exists(abs_filedir):
                os.makedirs(abs_filedir)

            abs_filepath = os.path.join(abs_filedir, file_name)  # 上传的压缩包的文件绝对存储路径
            # 将上传文件写入到本地
            f = open(abs_filepath, 'wb')
            f.write(file.read())
            f.close()

            # 读取excel start
            wb = xlrd.open_workbook(abs_filepath)
            sheet = wb.sheet_by_index(0)

            if sheet.ncols == 8 or sheet.ncols == 9 or sheet.ncols == 10:  # 8或9或10
                for row in range(sheet.nrows):
                    if row > 0:
                        try:
                            row_cols = sheet.row_values(row)  # 类型是list， 一行数据

                            code = str(row_cols[0]).strip()  # 摄像头编号
                            nickname = str(row_cols[1]).strip()  # 摄像头昵称
                            pull_stream_url = str(row_cols[2]).strip()  # 摄像头拉流地址
                            pull_stream_ip = str(row_cols[3]).strip()  # ip

                            try:
                                pull_stream_port = int(row_cols[4])  # port
                            except:
                                pull_stream_port = 554

                            username = str(row_cols[5]).strip()  # username
                            password = str(row_cols[6]).strip()  # password
                            remark = str(row_cols[7]).strip()

                            try:
                                is_audio = int(row_cols[8])  # is_audio
                            except:
                                is_audio = 0
                            try:
                                camera_device_id = str(row_cols[9]).strip()  # v4.638新增
                            except:
                                camera_device_id = code

                            d = {
                                'code': code,
                                'nickname': nickname,
                                'pull_stream_url': pull_stream_url,
                                'pull_stream_ip': pull_stream_ip,
                                'pull_stream_port': pull_stream_port,
                                'username': username,
                                'password': password,
                                'remark': remark,
                                'is_audio': is_audio,
                                'camera_device_id': camera_device_id
                            }
                            __data.append(d)
                        except:
                            pass

                __ret = True
                __msg = "success"
            else:
                __msg = "xlsx列数不正确"
            # 读取excel end

            if os.path.exists(abs_filedir):
                shutil.rmtree(abs_filedir)  # 删除文件夹及其内部所有子文件
        else:
            __msg = "上传文件格式必须是.xlsx"

        return __ret, __msg, __data

